<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>发票列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索 -->
        <el-form :inline="true" style="margin-top: 20px;">
            <el-form-item>
                <el-button size="small" @click="exportExcel">导出Excel</el-button>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="invoiceTitle" placeholder="请输入发票抬头"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="num" placeholder="请输入税号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="bank" placeholder="请输入开户银行"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="content" placeholder="请输入发票内容"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="status" placeholder="请选择发票状态">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker size="small" v-model="startTime" align="right" type="date" placeholder="选择时间（年/月/日）"
                    :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <!-- <el-form-item>
          <el-date-picker
          size="small"
          v-model="endTime"
          align="right"
          type="date"
          placeholder="搜索结束时间（年/月/日）"
          :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item> -->
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="chongzhi">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table size="small" ref="multipleTable" :data="invoiceData" element-loading-text="拼命加载中" style="width: 100%;"
            v-horizontal-scroll>
            <el-table-column align="center" sortable type="index" label="序号"></el-table-column>
            <el-table-column align="center" sortable prop="invoiceTitle" label="发票抬头" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="status" :formatter="Status" label="发票状态"
                width="120"></el-table-column>
            <el-table-column align="center" sortable prop="num" label="税号" width="200"></el-table-column>
            <el-table-column align="center" sortable prop="phone" label="手机号" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="address" label="企业地址" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="bank" label="开户银行" width="150"></el-table-column>
            <el-table-column align="center" sortable prop="bankNum" label="银行账号" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="content" label="发票内容" width="150"></el-table-column>
            <el-table-column align="center" sortable prop="money" label="发票金额" width="150">
                <template slot-scope="scope">
                    <div>{{ scope.row.money / 100 }}</div>
                </template>
            </el-table-column>

            <el-table-column align="center" sortable prop="email" label="电子邮箱" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="tel" label="联系电话" width="140"></el-table-column>
            <el-table-column align="center" sortable prop="url" label="发票图片" width="120">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 0">待开票</span>
                    <el-image v-else-if="scope.row.url" style="width: 60px;" :src="scope.row.url"
                        :preview-src-list="[scope.row.url]"></el-image>
                    <div v-else-if="scope.row.url == null">没有图片</div>
                    <span v-else-if="scope.row.status == 2">退回</span>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="remark" label="退回原因" width="140">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 0">待开票</span>
                    <span v-if="scope.row.status == 1">已开票</span>
                    <span v-if="scope.row.status == 2">{{ scope.row.remark }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="createTime" label="创建时间" width="150">
                <template slot-scope="scope">
                    <div>{{ transformDate(scope.row.createTime) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="openInvoice(scope.row)">查看详情</el-button>
                    <el-button v-if="scope.row.status != 0" size="mini" type="info" disabled>已审核</el-button>
                    <el-button v-if="scope.row.status == 0" size="mini" type="primary"
                        @click="upShenhe(scope.row)">审核发票</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 查看详情 -->
        <el-dialog title="发票详情页：" :visible.sync="editFormDetails">
            <el-form label-width="120px">
                <el-form-item label="发票抬头：" prop="invoiceTitle">
                    <span v-html="this.Details.invoiceTitle"></span>
                </el-form-item>
                <el-form-item label="税号：" prop="num">
                    <span v-html="this.Details.num"></span>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone">
                    <span v-html="this.Details.phone"></span>
                </el-form-item>
                <el-form-item label="企业地址：" prop="address">
                    <span v-html="this.Details.address"></span>
                </el-form-item>
                <el-form-item label="开户银行：" prop="bank">
                    <span v-html="this.Details.bank"></span>
                </el-form-item>
                <el-form-item label="银行账号：" prop="bankNum">
                    <span v-html="this.Details.bankNum"></span>
                </el-form-item>
                <el-form-item label="发票内容：" prop="content">
                    <span v-html="this.Details.content"></span>
                </el-form-item>
                <el-form-item label="发票金额：" prop="money">
                    <span v-html="this.Details.money"></span>
                </el-form-item>
                <el-form-item label="发票状态：" prop="status">
                    <span v-if="this.Details.status == 0">待开票</span>
                    <span v-if="this.Details.status == 1">已开票</span>
                    <span v-if="this.Details.status == 2">退回</span>
                </el-form-item>
                <el-form-item label="电子邮箱：" prop="email">
                    <span v-html="this.Details.email"></span>
                </el-form-item>
                <el-form-item label="联系电话：" prop="tel">
                    <span v-html="this.Details.tel"></span>
                </el-form-item>
                <el-form-item label="发票图片：" v-if="this.Details.status == 1">
                    <el-image v-if="this.Details.url" style="width: 140px; margin-left: 14px;" :src="this.Details.url"
                        :preview-src-list="[this.Details.url]"></el-image>
                </el-form-item>
                <el-form-item label="退回原因：" v-if="this.Details.status == 2">
                    <span v-html="this.Details.remark"></span>
                </el-form-item>
                <el-form-item label="创建时间：" prop="createTime">
                    {{ transformDate(this.Details.createTime) }}
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 审核发票-->
        <el-dialog title="审核发票申请界面" :visible.sync="editFormUpShenhe" width="30%">
            <el-form label-width="80px">
                <el-form-item label="审核状态">
                    <el-select v-model="shenhe" placeholder="请选择审核状态">
                        <el-option v-for="item in options1" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发票图片" v-if="shenhe == 1">
                    <div style="display: flex; align-items: center;">
                        <el-upload action="" :http-request="mainImgUpload" :show-file-list="false" list-type="picture-card">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-image v-if="url" style="width: 140px;height: 140px;margin-left: 14px;" :src="url"
                            :preview-src-list="[url]"></el-image>
                    </div>
                </el-form-item>
                <el-form-item label="退回原因" v-if="shenhe == 2">
                    <el-input size="small" v-model="remark" auto-complete="off" placeholder="请输入退回原因 "></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click='closeUpShenhe()'>取消</el-button>
                <el-button size="small" type="primary" :loading="loading" @click="upShenheFap()">确定</el-button>
            </div>
        </el-dialog>
        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    </div>
</template>

<script>
import {
    getAdminInvoiceList,
    getAdminInvoiceInfo,
    aduitInvoice
} from "../../api/userMG";
import client from "@/utils/ossClient.js";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import Pagination from '../../components/Pagination'
export default {
    data() {
        return {
            invoiceData: [],
            loading: false,
            invoiceTitle: '',
            num: '',
            phone: '',
            bank: '',
            content: '',
            status: '',
            options: [{
                value: 0,
                label: '待开票'
            }, {
                value: 1,
                label: '已开票'
            }, {
                value: 2,
                label: '退回'
            }],
            options1: [{
                value: 1,
                label: '已开票'
            }, {
                value: 2,
                label: '退回'
            }],
            startTime: '',
            endTime: '',
            timestamp: '',
            timestamps: '',
            editFormDetails: false,
            Details: [],
            editFormUpShenhe: false,
            shenhe: '',
            url: '',
            remark: '',
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 20,
                total: 10
            },
        }
    },
    created() {
        this.getdata(Number(localStorage.getItem("invoicePage")) || 1);
    },
    // 注册组件
    components: {
        Pagination
    },
    methods: {
        exportExcel() {
            var parameter = {
                page: -2,
                invoiceTitle: this.invoiceTitle,
                num: this.num,
                phone: this.phone,
                bank: this.bank,
                content: this.content,
                status: this.status,
                startTime: this.timestamp,
                endTime: this.timestamps,
            };
            getAdminInvoiceList(parameter).then((res) => {
                this.loading = false;
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg,
                    });
                } else {
                    this.invoiceData = res.data.list;
                    return;
                }
            })
            setTimeout(() => {
                //转换成excel时，使用原始的格式
                var xlsxParam = { raw: true };
                let fix = document.querySelector(".el-table__fixed-right");
                let wb;
                //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
                if (fix) {
                    wb = XLSX.utils.table_to_book(
                        this.$refs.multipleTable.$el.removeChild(fix), xlsxParam
                    );
                    this.$refs.multipleTable.$el.appendChild(fix);
                } else {
                    wb = XLSX.utils.table_to_book(this.$refs.multipleTable.$el, xlsxParam);
                }
                var wbout = XLSX.write(wb, {
                    bookType: "xls",
                    bookSST: true,
                    type: "array",
                });
                try {
                    // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
                    if (navigator.msSaveBlob) {
                        navigator.msSaveBlob(new Blob([wbout], { type: 'application/octet-stream' }), '发票列表.xlsx');
                    } else {
                        // 在其他浏览器中使用file-saver保存文件
                        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '发票列表.xlsx');
                    }
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout);
                }
                return wbout;
            }, 1000);
            setTimeout(() => {
                this.getdata(1)
            }, 2000);
        },
        // 发票状态
        Status: function (row) {
            if (row.status == 0) {
                return '待开票'
            } else if (row.status == 1) {
                return '已开票'
            } else if (row.status == 2) {
                return '退回'
            }
        },
        // 自定义上传方法 图片的
        mainImgUpload(file) {
            // 判断扩展名
            const tmpcnt = file.file.name.lastIndexOf(".");
            const exname = file.file.name.substring(tmpcnt + 1);
            const names = ["jpg", "jpeg", "webp", "png", "bmp"];
            if (names.indexOf(exname) < 0) {
                this.$message.error("不支持的格式!");
                return;
            }
            const fileName = file.file.uid + "." + exname;
            client
                .put(fileName, file.file)
                .then((res) => {
                    if (res.url) {
                        this.url = res.url
                    } else {
                        this.$message.error("文件上传失败");
                    }
                })
                .catch((err) => { });
        },
        // 修改审核状态
        upShenheFap() {
            let data = {
                id: this.id,
                status: this.shenhe,
                url: this.url,
                remark: this.remark
            }
            aduitInvoice(data).then((res) => {
                if (res.code == 200) {
                    this.editFormUpShenhe = false
                    this.$message.success(res.msg)
                    localStorage.setItem("invoicePage", this.pageparm.currentPage);
                    location.reload()
                } else {
                    this.editFormUpShenhe = false
                    this.$message.error(res.msg);
                }
            })
        },
        // 关闭审核编辑页
        closeUpShenhe() {
            this.editFormUpShenhe = false
            this.shenhe = ''
            this.remark = ''
            this.$message({
                type: 'info',
                message: '已取消修改'
            })
        },
        // 打开审核编辑页
        upShenhe(row) {
            this.editFormUpShenhe = true;
            this.id = row.id;
            return
            var userdata = JSON.parse(localStorage.getItem("userdata"))
            this.$prompt('请输入密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^(?!(\s+$))/,
                inputErrorMessage: '不可以空数据提交!'
            }).then(({ value }) => {
                if (value === userdata.menuTwo) {
                    this.editFormUpShenhe = true;
                    this.id = row.id;
                } else {
                    this.$message({
                        type: 'error',
                        message: '密码错误'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });
            });
        },
        // 打开详情页面
        openInvoice(row) {
            this.loading = true;
            this.editFormDetails = true;
            let data = {
                id: row.id
            }
            getAdminInvoiceInfo(data).then((res) => {
                this.loading = false;
                console.log(res)
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg
                    });
                } else {
                    this.Details = res.data.data;
                    return;
                }
            })
        },
        // 重置数据
        chongzhi() {
            this.invoiceTitle = ''
            this.num = ''
            this.phone = ''
            this.bank = ''
            this.status = ''
            this.timestamp = ''
            this.timestamps = ''
            this.startTime = ''
            this.endTime = ''
            this.getdata(1)
        },
        // 搜索数据
        search() {
            if (this.startTime != '') {
                this.timestamp = Math.floor(new Date(this.startTime).getTime() / 1000)
            }
            if (this.endTime != '') {
                this.timestamps = Math.floor(new Date(this.endTime).getTime() / 1000)
            }
            this.getdata(1);
        },
        // 分页插件事件
        callFather(parm) {
            this.pageparm.page = parm.currentPage
            this.getdata(parm.currentPage)
        },
        // 获取数据
        getdata(page) {
            this.loading = true;
            var parameter = {
                page: (page - 1) * 20,
                invoiceTitle: this.invoiceTitle,
                num: this.num,
                phone: this.phone,
                bank: this.bank,
                content: this.content,
                status: this.status,
                startTime: this.timestamp,
                endTime: this.timestamps,
            };
            getAdminInvoiceList(parameter).then((res) => {
                this.loading = false;
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg,
                    });
                } else {
                    this.invoiceData = res.data.list;
                    this.pageparm.currentPage = page;
                    this.pageparm.total = res.data.count;
                    return;
                }
            })
        },
    }

}
</script>

<style></style>